package cmd

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"

	"github.com/spf13/cobra"
)

// healthCmd represents the health command
func create_file_form(file string, fields map[string]string) (string, *bytes.Buffer, error) {
	handle, err := os.Open(file)
	if err != nil {
		fmt.Printf("Open File Failed: %v\n", err)
		return "", nil, err
	}
	defer handle.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	if fields != nil {
		for key, value := range fields {
			err := writer.WriteField(key, value)
			if err != nil {
				fmt.Printf("Write Form File To Body: %v\n", err)
				return "", nil, err
			}
		}
	}

	part, err := writer.CreateFormFile("file", filepath.Base(file))
	if err != nil {
		fmt.Printf("Create Form File Failed: %v\n", err)
		return "", nil, err
	}
	_, err = io.Copy(part, handle)
	if err != nil {
		fmt.Printf("Write Form File To Body Failed: %v\n", err)
		return "", nil, err
	}

	writer.Close()
	return writer.FormDataContentType(), body, nil
}

var service_pushCmd = &cobra.Command{
	Use: "push",
	Run: func(cmd *cobra.Command, args []string) {
		name, _ := cmd.Flags().GetString("name")
		node, _ := cmd.Flags().GetString("node")
		file, _ := cmd.Flags().GetString("file")
		fields := make(map[string]string)
		fields["name"] = name
		fields["node"] = node
		content_type, body, err := create_file_form(file, fields)
		if err != nil {
			return
		}
		client := http.Client{}
		req, err := http.NewRequest("POST", cmd_url_prefix+"/api/service/push", body)
		if err != nil {
			fmt.Printf("创建请求失败: %v\n", err)
			return
		}
		req.Header.Set("Content-Type", content_type)
		resp, err := client.Do(req)
		if err != nil {
			fmt.Printf("请求失败: %v\n", err)
			return
		}
		defer resp.Body.Close()
		buf, _ := ioutil.ReadAll(resp.Body)
		fmt.Print(string(buf))
	},
}

var package_pushCmd = &cobra.Command{
	Use: "push",
	Run: func(cmd *cobra.Command, args []string) {
		file, _ := cmd.Flags().GetString("file")
		content_type, body, err := create_file_form(file, nil)
		if err != nil {
			return
		}
		client := http.Client{}
		req, err := http.NewRequest("POST", cmd_url_prefix+"/api/package/push", body)
		if err != nil {
			fmt.Printf("创建请求失败: %v\n", err)
			return
		}
		req.Header.Set("Content-Type", content_type)
		resp, err := client.Do(req)
		if err != nil {
			fmt.Printf("请求失败: %v\n", err)
			return
		}
		defer resp.Body.Close()
		buf, _ := ioutil.ReadAll(resp.Body)
		fmt.Print(string(buf))
	},
}

func init() {
	serviceCmd.AddCommand(service_pushCmd)
	service_pushCmd.Flags().String("name", "", "service name")
	service_pushCmd.Flags().String("node", "", "node name")
	service_pushCmd.Flags().String("file", "", "file path")
	service_pushCmd.MarkFlagRequired("file")

	package_pushCmd.Flags().String("file", "", "file path")
	package_pushCmd.MarkFlagRequired("file")

	packageCmd.AddCommand(package_pushCmd)
}
